package com.atguigu.lease.web.app.custom.intercepter;

import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import io.jsonwebtoken.Claims;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import io.minio.credentials.Jwt;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Marco
 * @Description
 * @date 2025/8/7 18:06
 * @email 3293336923@qq.com
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        从  请求头 中 获取   token
        String token = request.getHeader("access-token");

//        解析 token
        Claims claims = JwtUtil.parseToken(token);
        Long  userId = claims.get("userId", Long.class);
        String userName = claims.get("username", String.class);

//    将  当前 登录的 用户信息 封装到 一个对象，保存在 一个 ThreadLocal 对象中
//    由于 后续 获取 当前 是哪一个用户在登陆，获取登录用户信息，进行数据回显

        LoginUserHolder.setLoginUser(new LoginUser(userId,userName));
        return   true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
